package com.shop.servlet.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
//import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import com.shop.security.filter.JwtAuthenticationFilter;

//import com.shop.servlet.handler.AuthenticationEntryPointHandler;

//import javax.annotation.Resource;
//

import com.shop.security.config.IgnoreUrlsConfig;
import com.shop.servlet.filter.JwtAuthenticationFilter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;
    // 安全过滤器链
//    @Bean
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        http
//                .csrf(csrf -> csrf.disable())
//                .sessionManagement(session -> session
//                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                )
//                .authorizeHttpRequests(auth -> auth
//                        // 免认证路径
//                        .requestMatchers(ignoreUrlsConfig.getUrls().toArray(new String[0])).permitAll()
//                        // 其他请求只需认证（无需角色权限）
//                        .anyRequest().authenticated()
//                )
//                .authenticationProvider(authenticationProvider())
//                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
//
//        return http.build();
//    }
    // 通用过滤器链：所有服务共享
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//        http.csrf().disable()
//                .cors().configurationSource(corsConfigurationSource()).and()
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
//                .authorizeRequests()
//                // 明确放行登录接口，避免权限拦截
//                .antMatchers(ignoreUrlsConfig.getUrls().toArray(new String[0])).permitAll()
//                // 其他接口需要认证
//                .anyRequest().authenticated();
        http.csrf().disable()
               // .cors().configurationSource(corsConfigurationSource()).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                // 明确放行登录接口，避免权限拦截
                .antMatchers(ignoreUrlsConfig.getUrls().toArray(new String[0])).permitAll()
                // 其他接口需要认证
                .anyRequest().authenticated();
//                .anyRequest().permitAll();
        // 确保JWT过滤器正确添加
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);


// 设置认证提供者
        http.authenticationProvider(authenticationProvider());

        return http.build();
    }

    // 跨域配置和网关重复设置
//    @Bean
//    public CorsConfigurationSource corsConfigurationSource() {
//        // 跨域配置（允许所有来源、方法、头）
//        return request -> {
//            CorsConfiguration config = new CorsConfiguration();
//            config.addAllowedOriginPattern("*");
//            config.addAllowedHeader("*");
//            config.addAllowedMethod("*");
//            config.setAllowCredentials(true);
//            return config;
//        };
//    }
    // 配置认证管理器
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }
    // 密码编码器（所有服务共享BCrypt）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private CommonSecurityConfig productSecurityConfig;
    // 配置认证提供者
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(productSecurityConfig.userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }
}
